package com.emuporium.gymrat.server.log;

import java.io.IOException;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.emuporium.gymrat.server.data.LogDB;

@SuppressWarnings("serial")
public class LogEditEntrySubmitServlet extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		


		String action = request.getParameter("action");
		
		String logId = request.getParameter("logId");
		String dateParam = request.getParameter("date");
		SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
		String variation = request.getParameter("variationBox");
		String equipment = request.getParameter("equipmentBox");
		String[] sets = request.getParameterValues("sets");

		if (action.equals("delete")) {
			LogDB.deleteLogEntry(new Integer(logId));
		} else {

			Date date;
			try {
				date = new Date(dateFormat.parse(dateParam).getTime());
			} catch (ParseException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				date = null;
			}

			ArrayList<String> setsList = new ArrayList<String>();

			for (String s : sets) {
				setsList.add(s);
			}

			String reps, weight, delete;

			for (String s : setsList) {
				reps = request.getParameter("reps_" + s);
				weight = request.getParameter("weight_" + s);
				delete = request.getParameter("delete_" + s);

				if (delete != null) {
					LogDB.deleteLogSet(new Integer(s));
				} else
					LogDB.updateLogSet(new Integer(s), new Integer(reps),
							new Integer(weight));
			}

			LogDB.updateLogEntry(new Integer(logId), date, new Integer(
					variation), new Integer(equipment));
		}

		request.setAttribute("redirecturl", "/log/view");
		String url = "/includes/redirect.jsp";
		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}

}
